package org.swift.commons.client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MeasuredInputStream extends InputStream {

	private final static Log log = LogFactory.getLog(MeasuredInputStream.class);

	private final long size;
	
	private final InputStream inputStream;
	private final ByteArrayOutputStream debugStream;
	
	public MeasuredInputStream(int contentLength,
			InputStream inputStream) {
		this.size = contentLength;
		this.inputStream = inputStream;
		debugStream = log.isDebugEnabled() ? new ByteArrayOutputStream(
				contentLength < 1 ? 2028 : contentLength) : null;
	}

	@Override
	public int read() throws IOException {
		final int thebyte = this.inputStream.read();
		if(log.isDebugEnabled() && debugStream != null) {
			if(thebyte == -1) {
				log.debug(debugStream.toString());
			}
			else {
				debugStream.write(thebyte);
			}
		}
		return thebyte;
	}

	@Override
	public void close() throws IOException {
		this.inputStream.close();
	}
	
	public long size() {
		return this.size;
	}
}
